package com.tensquare.spit.service;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.repository.SpitRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;
import java.util.List;

/**
 * @program: tensquare_parent
 * @description: 吐槽服务层
 * @author: NieMiao
 * @create: 2018-12-26 16:56
 **/
@Service
public class SpitService {
    @Autowired
    private SpitRepository spitRepository;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询全部记录
     * @return
     */
    public List<Spit> findAll(){
        return spitRepository.findAll();
    }

    public Spit findById(String id){
        Spit spit = spitRepository.findById(id).get();
        return spit;
    }

    public void add(Spit spit) {
        spit.set_id(idWorker.nextId()+""); //主键值
        spitRepository.save(spit);
    }

    public void update(Spit spit) {
        spitRepository.save(spit);
    }

    public void deleteById(String id) {
        spitRepository.deleteById(id);
    }
    /** 
    * @Description: 根据父节点id查询
    * @Param: [id, page, size] 
    * @return: org.springframework.data.domain.Page<com.tensquare.spit.pojo.Spit> 
    * @Author: NieMiao 
    * @Date: 2018/12/28 
    */ 
    public Page<Spit> findByParentId(String id,Integer page,Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return spitRepository.findByParentid(id,pageable);
    }

    public void updateThumbup(String id){
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup",1);
        mongoTemplate.updateFirst(query,update,"spit");
    }
}
